package com.wawu.server.dao;

import com.wawu.common.annotation.IOC.component.Repository;
import com.wawu.common.exception.BaseException;
import com.wawu.common.utils.SQLBuilder.SelectSQLBuilder;
import com.wawu.common.utils.SQLBuilder.UpdateSQLBuilder;
import com.wawu.common.utils.SQLExcutorUtil;
import com.wawu.pojo.entity.GoodDetail;

import java.sql.SQLException;
import java.util.List;

@Repository
public class GoodsDetailsDAO {


    /**
     * 动态条件查询商品详情表
     * @param goodDetailQuery
     * @return
     */
    public List<GoodDetail> getGoodDetails(GoodDetail goodDetailQuery) throws SQLException {
        SelectSQLBuilder selectSqlBuilder = new SelectSQLBuilder("goodsDetails")
                .addDynamicCondition("id", "=", goodDetailQuery.getId())
                .addDynamicCondition("goodsId", "=", goodDetailQuery.getGoodsId());
        return SQLExcutorUtil.queryList(selectSqlBuilder.getSQL(),GoodDetail.class, selectSqlBuilder.getParams());

    }

    //查单个
    public GoodDetail getGoodDetailByGoodId(Long goodId) throws SQLException {
        SelectSQLBuilder sqlBuilder=new SelectSQLBuilder("goodsDetails")
                .addDynamicCondition("goodsId","=", goodId);
        System.out.println(sqlBuilder.getSQL());
        return SQLExcutorUtil.querySingle(sqlBuilder.getSQL(),GoodDetail.class,sqlBuilder.getParams());
    }


    //获取商品资料
    public List<GoodDetail> getGoodDetailsByGoodId(Long goodId) throws SQLException {
        SelectSQLBuilder sqlBuilder=new SelectSQLBuilder("goodsDetails")
                .addDynamicCondition("goodsId","=", goodId);
        System.out.println(sqlBuilder.getSQL());
        return SQLExcutorUtil.queryList(sqlBuilder.getSQL(),GoodDetail.class,sqlBuilder.getParams());
    }

    /**
     * 根据商品获取单价
     * @param goodsId
     * @return
     * @throws SQLException
     */
    public float getPriceByGoodsId(Long goodsId) throws SQLException {
        String sql="SELECT unitPrice FROM goodsDetails WHERE goodsId = ? LIMIT 1";
        Float price = SQLExcutorUtil.queryScalar(sql,Float.class,goodsId);
        return price != null ? price : 0.0f;
    }

    /**
     * 通过id获取规格名称
     * @param id
     * @return
     * @throws SQLException
     */
    public String getSpecNameById(Long id) throws SQLException {
        String sql="SELECT specName FROM goodsDetails WHERE id = ? LIMIT 1";
        return SQLExcutorUtil.queryScalar(sql,String.class,id);
    }

    /**
     * 根据id更新商品详情（目前只设置个库存）
     * @param goodDetail
     */
    public void update(GoodDetail goodDetail){
        //先限制整一个异常，后续在搞吧，没啥时间了
        if(goodDetail.getId()==null){
            throw new BaseException("商品详情id为空，无法继续");
        }
        UpdateSQLBuilder updateSQLBuilder=new UpdateSQLBuilder("goodsdetails")
                .setField("specName",goodDetail.getSpecName())
                .setField("stockNum",goodDetail.getStockNum())
                .setField("unitPrice",goodDetail.getUnitPrice())
                .setField("updatetime",goodDetail.getUpdateTime())
                .addDynamicCondition("id","=",goodDetail.getId());//TODO: 待优化：这里不应该整成动态条件的

        //这里异常其实可以先不加的
        try {
            // 调用 SQLExcutorUtil 的 update 方法执行更新
            int rowsAffected = SQLExcutorUtil.update(updateSQLBuilder.getSQL(), updateSQLBuilder.getParams());
            if (rowsAffected == 0) {
                throw new BaseException("更新失败，未找到对应的记录");
            }
        } catch (SQLException e) {
            throw new BaseException("数据库更新操作失败"+e);
        }

    }


    public static void main(String[] args) throws SQLException {
        GoodsDetailsDAO goodsDetailsDAO=new GoodsDetailsDAO();
//        GoodDetail goodDetailByGoodId = goodsDetailsDAO.getGoodDetailByGoodId(null);
//        System.out.println(goodDetailByGoodId);
//
//        goodDetailByGoodId = goodsDetailsDAO.getGoodDetailByGoodId(9L);
//        System.out.println(goodDetailByGoodId);

        float priceByGoodsId = goodsDetailsDAO.getPriceByGoodsId(10L);
        System.out.println(priceByGoodsId);

    }


    //TODO 待优化：插入时，使用反射跟字段对应
    /**
     * 插入商品详情返回主键
     * @param goodDetail
     * @return
     */
    public Long insert(GoodDetail goodDetail) throws SQLException {
        String sql="INSERT INTO `goodsDetails` (`goodsId`,`specName`,`stockNum`,`unitPrice`,`updatetime`,`createtime`) " +
                "VALUES (?,?,?,?,?,?)";
        return SQLExcutorUtil.updateAndGetGeneratedKey(sql,goodDetail.getGoodsId(),goodDetail.getSpecName(),goodDetail.getStockNum(),goodDetail.getUnitPrice(),goodDetail.getUpdateTime(),goodDetail.getCreateTime());
    }

    public Integer deleteByGoodId(Long goodId) throws SQLException {
        String sql="DELETE FROM `goodsDetails` WHERE `goodsId` = ?";
        return SQLExcutorUtil.update(sql,goodId);
    }
}
